<template>
  <div>
    <Drawer
      :title="title"
      v-model="visible"
      width="720"
      :mask-closable="true"
      :styles="styles"
    >
      <Form :model="form" ref="userForm" :rules="userRules">
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="用户账号"  prop="username" label-position="top">
              <Input v-model="form.username" placeholder="请输入用户账号" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="手机号码" prop="phone" label-position="top">
              <Input v-model="form.phone" placeholder="请输入手机号码"/>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="性别"  prop="gender" label-position="top">
              <Select v-model="form.gender" clearable  placeholder="请选择性别">
                <Option value="1">男</Option>
                <Option value="2">女</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="出生日期" prop="birthday" label-position="top">
              <DatePicker type="date" format="yyyy-MM-dd" v-model="form.birthday" style="display: block" placeholder="请选择出生日期"></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32" v-if="!form.userId">
          <Col span="12">
            <FormItem label="密码" prop="password" label-position="top">
              <Input v-model="form.password" type="password" placeholder="请输入密码"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="确认密码" prop="confirmPassword" label-position="top">
              <Input v-model="form.confirmPassword" type="password"  placeholder="请再次输入密码"/>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="邮箱" prop="email" label-position="top">
              <Input v-model="form.email" placeholder="请输入邮箱"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="角色" prop="selectedRole" label-position="top">
              <Select v-model="form.selectedRole" clearable  multiple placeholder="请选择角色">
                <Option v-for="item in roleList" :value="item.roleId" :key="item.roleId">{{ item.roleName }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="用户部门" prop="deptId" label-position="top" :error="errorMsg">
              <dept-tree-select @on-change="changeDept" ref="deptTree"></dept-tree-select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="用户岗位" prop="jobId" label-position="top">
              <Select v-model="form.jobId" clearable placeholder="请选择岗位">
                <Option v-for="item in jobList" :value="item.jobId" :key="item.jobId">{{ item.jobName }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="简介" prop="remark" label-position="top">
          <Input type="textarea" v-model="form.remark" :rows="4" placeholder="请输入个人简介" />
        </FormItem>
      </Form>
      <div class="demo-drawer-footer">
        <Button type="primary" style="margin-right: 8px" :loading="submitLoading" @click="submitForm">{{$t("submit")}}</Button>
        <Button  @click="close">{{$t("close")}}</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import {findRoleList} from "@/api/role";;
import {findJobList} from "@/api/job";
import {checkUniqueness,saveUser,updateUser} from "@/api/user";
import deptTreeSelect from '@/components/base/dept-tree-select'
export default {
  name: "UserForm",
  components:{
    deptTreeSelect
  },
  data(){
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else {
        callback();
      }
    };
    const validateConfirmPass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else if(this.form.password!=value) {
        callback(new Error("两次输入的密码不一致"));
      }else{
        callback()
      }
    };
    const validateUsername = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,16}$/;
      if (value.length > 16) {
        callback(new Error('长度不能超过16个字符'));
      } else if (!reg.test(value)) {
        callback(new Error('仅支持大小写英文、中文和下划线_'));
      } else {
        checkUniqueness({value:value,oldValue:this.oldUsername}).then(res=>{
          if(res.data){
            callback(new Error("用户名已存在"));
          }else{
            callback();
          }
        })
      }
    };
    const validatePhone=(rule, value, callback)=>{
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error('手机号格式错误'));
      } else {
        checkUniqueness({value:value,oldValue:this.oldPhone}).then(res=>{
          if(res.data){
            callback(new Error("手机号码已存在"));
          }else{
            callback()
          }
        })
      }
    }
    const validateEmail=(rule, value, callback)=>{
      let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if(typeof(value)!='undefined'){
        if (!reg.test(value)) {
          callback(new Error('邮箱格式不正确'));
        } else {
          callback();
        }
      }else{
        callback()
      }
    }
    return{
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      title:'添加',
      submitLoading:false,
      form:{},
      visible: false,
      oldUsername:'',
      oldPhone:'',
      errorMsg:'',
      userRules:{
        username:[
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          {validator:validateUsername}
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          {validator:validatePass}
        ],
        selectedRole:[
          { type: 'array',required: true, message: '请选择角色', trigger: 'change' }
        ],
        email:[
          {validator:validateEmail}
        ],
        phone:[
          {validator:validatePhone}
        ],
        confirmPassword:[
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {validator:validateConfirmPass}
        ],
        jobId:[
          {required:true,message:'请选择岗位',trigger:'change'}
        ],
        gender:[
          {required:true,message:'请选择性别',trigger:'change'}
        ],
        birthday:[
          {type:'date',required:true,message:'请选择出生日期',trigger:'change'}
        ]
      },
      roleList:[],
      deptData:[],
      jobList:[]
    }
  },
  methods:{
    add(){
      this.edit({})
    },
    edit(record){
      this.$refs['userForm'].resetFields();
      this.form= {}
      this.getRoleList();
      // this.getDeptTreeData();
      this.getJobList();
      if (Object.keys(record).length !== 0) {
        this.form.userId=record.userId;
        this.form.username=record.username;
        this.form.phone=record.phone;
        this.form.email=record.email;
        this.form.remark=record.remark;
        this.form.birthday=record.birthday;
        this.form.gender=record.gender;
        this.oldUsername=record.username;
        this.oldPhone=record.phone;
        this.form.jobId=record.jobId;
        let roleList=record.roles;
        this.$refs.deptTree.setData(record.deptId,record.deptName)
        let selectRoles=[];
        for(let item of roleList){
           selectRoles.push(item.roleId);
        }
        this.form.selectedRole=selectRoles;
        this.form.selectedDept=record.deptId.split(",");

      }
      this.visible = true
    },
    getRoleList(){
      findRoleList().then(res=>{
        if(res.code===200){
           this.roleList=res.data;
        }
      })
    },
    changeDept(v){
      this.form.deptId=v;
    },
    getJobList(){
      findJobList().then(res=>{
        if(res.code===200){
           this.jobList=res.data;
        }
      })
    },
    submitForm(){
      if(this.form.deptId===''||this.form.deptId==null){
         this.errorMsg="请选择部门";
         return;
      }else{
        this.errorMsg="";
      }
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          this.submitLoading=true;
          let formData = Object.assign(this.form, {})
          const userRoles=[];
          for(let item of this.form.selectedRole){
            userRoles.push(item);
          }
          formData.roleList=userRoles;
          formData.deptId=this.form.selectedDept[this.form.selectedDept.length-1];
          let obj;
          if(!this.form.userId){
            obj=saveUser(formData);
          }else{
           obj=updateUser(formData);
          }
          obj.then(res=>{
            console.log(res)
            if(res.code===200){
              this.submitLoading=false
              this.$emit('ok')
            }
          }).catch((error)=>{
            this.submitLoading=false
          }).finally(()=>{
            this.submitLoading=false
            this.close()
          })
        }
      }).catch((error)=>{
        console.log(error)
      })
    },
    close(){
      this.visible=false;
      this.submitLoading=false;
    },
    changeBirth(v){
      this.form.birthday=v;
    },
    // selectDept(value){
    //   if(value.length>0){
    //      let deptId=value[value.length-1]
    //      this.form.deptId=deptId;
    //   }
    // }
  }
}
</script>

<style scoped>
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>
